// pages/userInfo/myHouse/myHouse.js
const app = getApp()
import api from '../../../config/api'
import path from '../../../config/path'
const { $Message } = require('../../../dist/base/index');
const { $Toast } = require('../../../dist/base/index');
Page({

  data: {
    picLocal: app.globalData.picLocal,
    baseHeadPic: app.globalData.picLocal + "/default/head/head.png",
    houseList: [],
    pageData: {
      pageNo: 1,
      pageSize: 10,
      total: 0,
      hasMore: true
    },
    bottomLoading: false,
    loading: true,
    activeTab: 0,
    userRole: 1, // 1-房主，2-管理员
    tabs: [],
    // 房主的标签页
    landlordTabs: [
      { name: '全部', value: 0 },
      { name: '待审核', value: 1 },
      { name: '已上架', value: 2 },
      { name: '已下架', value: 3 },
      { name: '审核失败', value: 4 }
    ],
    // 管理员的标签页
    adminTabs: [
      { name: '待审核', value: 1 },
      { name: '已审核', value: 2 },
      { name: '已拒绝', value: 3 }
    ]
  },

  onLoad: function (options) {
    // 获取用户角色
    const userInfo = wx.getStorageSync('userInfo')
    const userRole = userInfo.role || 1
    this.setData({ userRole })
    
    // 设置页面标题和标签页
    if (userRole === 2) {
      wx.setNavigationBarTitle({ title: '房源审核' })
      this.setData({ tabs: this.data.adminTabs })
    } else {
      wx.setNavigationBarTitle({ title: '我的房源' })
      this.setData({ tabs: this.data.landlordTabs })
    }
    
    this.fetchMyHouses(true)
  },

  onReachBottom: function () {
    // 如果没有更多数据，直接返回
    if (!this.data.pageData.hasMore) {
      $Toast({
        content: '没有更多数据了'
      })
      return;
    }
    
    this.bottomStart();
    
    this.data.pageData.pageNo++;
    this.setData({
      pageData: this.data.pageData
    })
    this.fetchMyHouses(false)
  },

  // 切换标签
  onTabChange(e) {
    const tabIndex = e.currentTarget.dataset.index
    this.setData({
      activeTab: tabIndex,
      houseList: [],
      pageData: {
        pageNo: 1,
        pageSize: 10,
        total: 0,
        hasMore: true
      },
      loading: true
    })
    this.fetchMyHouses(true)
  },

  // 跳转到房源详情
  toHouseInfo(e) {
    const houseId = e.currentTarget.dataset.id
    if (!houseId) {
      $Toast({ content: '房源信息有误' })
      return
    }
    wx.navigateTo({
      url: '../../index/houseInfo/houseInfo?id=' + houseId,
    })
  },

  // 编辑房源 - 仅房主
  editHouse(e) {
    if (this.data.userRole !== 1) {
      $Toast({ content: '无操作权限' })
      return
    }
    
    const houseId = e.currentTarget.dataset.id
    
    // 跳转到编辑页面，传递房源ID
    wx.navigateTo({
      url: '/pages/userInfo/myhouse/abouthouse/abouthouse?id=' + houseId,
    })
  },

  // 删除房源 - 仅房主
  deleteHouse(e) {
    if (this.data.userRole !== 1) {
      $Toast({ content: '无操作权限' })
      return
    }
    
    const houseId = e.currentTarget.dataset.id
    const houseTitle = e.currentTarget.dataset.title
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除房源"${houseTitle}"吗？`,
      confirmColor: '#d81e06',
      success: (res) => {
        if (res.confirm) {
          this.handleDelete(houseId)
        }
      }
    })
  },

  // 审核房源 - 仅管理员
  auditHouse(e) {
    if (this.data.userRole !== 2) {
      $Toast({ content: '无操作权限' })
      return
    }
    
    const houseId = e.currentTarget.dataset.id
    const action = e.currentTarget.dataset.action // 1-通过，2-拒绝
    const houseTitle = e.currentTarget.dataset.title
    
    console.log('审核操作:', { houseId, action, houseTitle })
    
    if (action == 1) {
      // 同意审核 - 直接确认通过
      wx.showModal({
        title: '确认通过',
        content: `确定要通过房源"${houseTitle}"的审核吗？`,
        confirmColor: '#07c160',
        success: (res) => {
          if (res.confirm) {
            this.handleAudit(houseId, 1, '审核通过')
          }
        }
      })
    } else if (action == 2) {
      // 拒绝审核 - 弹出输入框要求填写原因
      wx.showModal({
        title: '审核拒绝',
        content: '请输入拒绝原因',
        editable: true,
        placeholderText: '请输入拒绝原因...',
        confirmColor: '#d81e06',
        success: (res) => {
          if (res.confirm) {
            const auditRemark = res.content || '审核不通过'
            this.handleAudit(houseId, 2, auditRemark)
          }
        }
      })
    }
  },

  // 处理审核
  async handleAudit(houseId, auditStatus, auditRemark) {
    wx.showLoading({ title: '审核中...' })
    
    try {
      // 根据后端接口，审核接口需要拼接参数
      let url = `${path.path.auditHouse}?id=${houseId}&auditStatus=${auditStatus}`
      if (auditRemark && auditStatus === 2) {
        url += `&auditRemark=${encodeURIComponent(auditRemark)}`
      }
      
      console.log('审核请求URL:', url)
      const res = await api.put('house', url, {})
      
      if (res.code === 200) {
        $Toast({
          content: auditStatus === 1 ? '审核通过' : '审核拒绝',
          icon: 'success'
        })
        // 重新加载列表
        this.setData({
          houseList: [],
          pageData: {
            pageNo: 1,
            pageSize: 10,
            total: 0,
            hasMore: true
          }
        })
        this.fetchMyHouses(true)
      } else {
        $Toast({
          content: res.message || '审核失败',
          type: 'error'
        })
      }
    } catch (err) {
      console.log('审核房源失败:', err)
      $Toast({
        content: '审核失败，请重试',
        type: 'error'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 处理删除
  async handleDelete(houseId) {
    wx.showLoading({ title: '删除中...' })
    
    try {
      const res = await api.remove('house', path.path.deleteHouse + houseId)
      if (res.code === 200) {
        $Toast({
          content: '删除成功',
          icon: 'success'
        })
        // 重新加载列表
        this.setData({
          houseList: [],
          pageData: {
            pageNo: 1,
            pageSize: 10,
            total: 0,
            hasMore: true
          }
        })
        this.fetchMyHouses(true)
      } else {
        $Toast({
          content: res.message || '删除失败',
          type: 'error'
        })
      }
    } catch (err) {
      console.log('删除房源失败:', err)
      $Toast({
        content: '删除失败，请重试',
        type: 'error'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 发布新房源 - 仅房主
  publishNewHouse() {
    if (this.data.userRole !== 1) {
      $Toast({ content: '无操作权限' })
      return
    }
    
    // 跳转到发布房源页面，不传递ID
    wx.navigateTo({
      url: '/pages/userInfo/myhouse/abouthouse/abouthouse',
    })
  },

  // 底部加载
  bottomStart() {
    this.setData({
      bottomLoading: true
    })
  },

  // 底部不加载
  bottomEnd() {
    this.setData({
      bottomLoading: false
    })
  },

  // 获取房源列表
  async fetchMyHouses(reset) {
    const { pageNo, pageSize } = this.data.pageData
    const { activeTab, userRole } = this.data
    
    try {
      let apiPath = path.path.myHouseResource
      let params = `?pageNo=${pageNo}&pageSize=${pageSize}`
      
      console.log('请求参数:', { userRole, activeTab, pageNo, pageSize })
      
      // 根据用户角色和标签状态设置参数
      if (userRole === 2) {
        // 管理员：根据标签筛选审核状态
        if (activeTab === 0) {
          // 待审核 - auditStatus=0
          params += '&auditStatus=0'
        } else if (activeTab === 1) {
          // 已审核 - auditStatus=1
          params += '&auditStatus=1'
        } else if (activeTab === 2) {
          // 已拒绝 - auditStatus=2
          params += '&auditStatus=2'
        }
      } else {
        // 房主：根据标签筛选房源状态
        if (activeTab === 0) {
          // 全部 - 不传特定状态参数，后端返回所有
          // 不添加任何状态参数
        } else if (activeTab === 1) {
          // 待审核 - auditStatus=0
          params += '&auditStatus=0'
        } else if (activeTab === 2) {
          // 已上架 - status=1 & auditStatus=1
          params += '&status=1&auditStatus=1'
        } else if (activeTab === 3) {
          // 已下架 - status=2
          params += '&status=2'
        } else if (activeTab === 4) {
          // 审核失败 - auditStatus=2
          params += '&auditStatus=2'
        }
      }
      
      console.log('API请求:', apiPath + params)
      const res = await api.get('house', apiPath + params)
      
      if (res.code !== 200) {
        throw new Error(res.message || '请求失败')
      }
      
      const page = res.data || {}
      const houseList = page.records || page.list || []
      const total = page.total || 0
      const currentPageSize = houseList.length

      console.log('分页数据:', { total, currentPageSize, pageNo, pageSize })

      // 计算是否有更多数据
      const hasMore = (pageNo * pageSize) < total

      // 如果没有数据
      if (houseList.length === 0) {
        this.setData({
          houseList: reset ? [] : this.data.houseList,
          pageData: {
            ...this.data.pageData,
            total: total,
            hasMore: hasMore
          },
          loading: false
        })
        this.bottomEnd()
        return
      }

      // 处理房源数据
      const processedHouses = houseList.map(house => this.normalizeHouseInfo(house))
      
      this.setData({
        houseList: reset ? processedHouses : this.data.houseList.concat(processedHouses),
        pageData: {
          ...this.data.pageData,
          total: total,
          hasMore: hasMore
        },
        loading: false
      })
      
    } catch (err) {
      console.log('获取房源列表失败:', err)
      $Toast({ 
        content: '加载失败: ' + (err.message || '未知错误'),
        type: 'error'
      })
      this.setData({ 
        loading: false,
        pageData: {
          ...this.data.pageData,
          hasMore: false
        }
      })
    } finally {
      this.bottomEnd()
    }
  },

  // 标准化房源信息
  normalizeHouseInfo(houseData) {
    // 解析设施信息
    let facilities = []
    try {
      facilities = houseData.facilities ? JSON.parse(houseData.facilities) : []
    } catch (e) {
      facilities = []
    }

    // 获取状态信息
    const status = houseData.status || 0
    const auditStatus = houseData.auditStatus || 0
    const statusInfo = this.getStatusInfo(status, auditStatus)
    
    return {
      id: houseData.id,
      title: houseData.title || '暂无标题',
      price: houseData.price || 0,
      description: houseData.description || '',
      roomType: houseData.roomType || '',
      province: houseData.province || '',
      city: houseData.city || '',
      district: houseData.district || '',
      address: houseData.address || '',
      area: houseData.area || '--',
      picList: (houseData.picList || []).map(pic => ({
        url: pic.url || pic.path || pic
      })),
      facilities: facilities,
      orientation: houseData.orientation || '未知',
      floor: houseData.floor || '--',
      totalFloor: houseData.totalFloor || '--',
      decoration: houseData.decoration || '未知',
      status: status,
      auditStatus: auditStatus,
      statusText: statusInfo.text,
      statusColor: statusInfo.color,
      createTime: houseData.createTime || '',
      updateTime: houseData.updateTime || '',
      auditRemark: houseData.auditRemark || '',
      viewCount: houseData.viewCount || 0,
      landlordId: houseData.landlordId || ''
    }
  },

  // 获取状态信息
  getStatusInfo(status, auditStatus) {
    // 审核状态优先
    if (auditStatus === 0) {
      return { text: '待审核', color: '#ff976a' }
    } else if (auditStatus === 2) {
      return { text: '审核失败', color: '#d81e06' }
    }
    
    // 房源状态
    if (status === 1) {
      return { text: '已上架', color: '#07c160' }
    } else if (status === 2) {
      return { text: '已下架', color: '#909399' }
    } else if (status === 3) {
      return { text: '已出租', color: '#1890ff' }
    } else {
      return { text: '未知', color: '#909399' }
    }
  },

  // 格式化时间
  formatTime(timeStr) {
    if (!timeStr) return ''
    try {
      const date = new Date(timeStr)
      const now = new Date()
      const diff = now - date
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      
      if (days === 0) {
        return '今天'
      } else if (days === 1) {
        return '昨天'
      } else if (days < 7) {
        return `${days}天前`
      } else {
        return `${date.getMonth() + 1}月${date.getDate()}日`
      }
    } catch (e) {
      return timeStr
    }
  }
})